package com.xinyu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinyu.config.FileStorageProperties;
import com.xinyu.domain.Lesson;
import com.xinyu.mapper.LessonMapper;
import com.xinyu.mapper.UserMapper;
import com.xinyu.service.ILessonService;
import com.xinyu.vo.BaseResult;
import com.xinyu.vo.LessonRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author l
 * @since 2025-02-20
 */
@Service
public class LessonServiceImpl extends ServiceImpl<LessonMapper, Lesson> implements ILessonService {

    @Autowired
    private LessonMapper lessonMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FileStorageProperties fileStorageProperties; // 注入配置类

    @Override
    public BaseResult queryByCondition(LessonRequest lessonRequest) {
        List<Lesson> list = lessonMapper.queryByCondition(lessonRequest);
        for (Lesson lesson : list) {
            if (lesson.getUser() != null && StringUtils.isNotBlank(lesson.getUser().getHead())
                    && !lesson.getUser().getHead().contains(fileStorageProperties.getBaseUrl())) {
                lesson.getUser().setHead(fileStorageProperties.getBaseUrl() + lesson.getUser().getHead());
            }
            applyPermissionMetadata(lesson);
        }
        Integer lessonCounts = lessonMapper.lessonCounts(lessonRequest);
        return BaseResult.ok(list,lessonCounts);
    }

    @Override
    public Lesson queryById(Integer id) {
        Lesson lesson = lessonMapper.selectById(id);
        if (lesson == null) {
            return null;
        }
        lesson.setUser(userMapper.selectById(lesson.getUserId()));
        if (lesson.getUser() != null && StringUtils.isNotBlank(lesson.getUser().getHead())) {
            lesson.getUser().setHead(fileStorageProperties.getBaseUrl() + lesson.getUser().getHead());
        }
        return lesson;
    }

    private void applyPermissionMetadata(Lesson lesson) {
        if (lesson == null) {
            return;
        }
        lesson.setCanDownloadAttachment(Boolean.TRUE);
        lesson.setDownloadDenyReason(null);
    }
}
